#!/usr/bin/env bash

#=======================================================================#
# Copyright (C) 2020 - 2024 Dominik Willner <th33xitus@gmail.com>       #
#                                                                       #
# This file is part of KIAUH - Klipper Installation And Update Helper   #
# https://github.com/dw-0/kiauh                                         #
#                                                                       #
# This file may be distributed under the terms of the GNU GPLv3 license #
#=======================================================================#

set -e
clear -x

# make sure we have the correct permissions while running the script
umask 022

### sourcing all additional scripts
KIAUH_SRCDIR="$(dirname -- "$(readlink -f "${BASH_SOURCE[0]}")")"
for script in "${KIAUH_SRCDIR}/scripts/"*.sh; do . "${script}"; done
for script in "${KIAUH_SRCDIR}/scripts/ui/"*.sh; do . "${script}"; done

#===================================================#
#=================== UPDATE KIAUH ==================#
#===================================================#

function update_kiauh() {
  status_msg "您的KIAUH酱正准备加载最新的系统哦..."

  cd "${KIAUH_SRCDIR}"
  git reset --hard && git pull

  ok_msg "您的KIAUH酱已经完成最新系统的版本更新！！尝试重启一下KIAUH酱吧！"
  exit 0
}

#===================================================#
#=================== KIAUH STATUS ==================#
#===================================================#

function kiauh_update_avail() {
  [[ ! -d "${KIAUH_SRCDIR}/.git" ]] && return
  local origin head

  cd "${KIAUH_SRCDIR}"

  ### abort if not on master branch
  ! git branch -a | grep -q "\* master" && return

  ### compare commit hash
  git fetch -q
  origin=$(git rev-parse --short=8 origin/master)
  head=$(git rev-parse --short=8 HEAD)

  if [[ ${origin} != "${head}" ]]; then
    echo "true"
  fi
}

function save_startup_version() {
  local launch_version

  echo "${1}"

  sed -i "/^version_to_launch=/d" "${INI_FILE}"
  sed -i '$a'"version_to_launch=${1}" "${INI_FILE}"
}

function kiauh_update_dialog() {
  [[ ! $(kiauh_update_avail) == "true" ]] && return
  top_border
  echo -e "|${green}              哇哦！发现 KIAUH酱 的新版本！              ${white}|"
  hr
  echo -e "|${green}  View Changelog: https://git.io/JnmlX                 ${white}|"
  blank_line
  echo -e "|${yellow}  为了更好地守护这个你的打印机，建议及时更新KIAUH酱哦！  ${white}|"
  echo -e "|${yellow}  更新通常包含修复、重要改动和新特性！   ${white}|"
  echo -e "|${yellow}  请考虑更新吧！                  ${white}|"
  bottom_border

  local yn
  read -p "${cyan}###### 你想要现在更新吗，回答Y/N? :${white} " yn
  while true; do
    case "${yn}" in
     Y|y|Yes|yes|"")
       do_action "update_kiauh"
       break;;
     N|n|No|no)
       break;;
     *)
       deny_action "kiauh_update_dialog";;
    esac
  done
}

function launch_kiauh_v5() {
    main_menu
}

function launch_kiauh_v6() {
  local entrypoint

  if ! command -v python3 &>/dev/null || [[ $(python3 -V | cut -d " " -f2 | cut -d "." -f2) -lt 8 ]]; then
    echo "您的python环境没有Python 3.8或者更高以上的版本 !"
    echo "请先安装 Python 3.8 或更高版本，再尝试运行KIAUH酱吧！"
    exit 1
  fi

  entrypoint=$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")

  export PYTHONPATH="${entrypoint}"

  clear -x
  python3 "${entrypoint}/kiauh.py"
}

function main() {
  read_kiauh_ini "${FUNCNAME[0]}"

  if [[ ${version_to_launch} -eq 5 ]]; then
    launch_kiauh_v5
  elif [[ ${version_to_launch} -eq 6 ]]; then
    launch_kiauh_v6
  else
    top_border
    echo -e "|         ${green}KIAUH v6.0.0-alpha1版本已经上线啦！${white}         |"
    hr
    echo -e "|         View Changelog: ${magenta}https://git.io/JnmlX${white}          |"
    blank_line
    echo -e "| KIAUH v6 是从零开始重构的全新版本,有需要的小伙伴可以去官方下载 |"
    echo -e "| 它基于 Python 3.8，带来了许多改进和新特性！   |"
    blank_line
    echo -e "| ${yellow}注意哦：v6 还处于测试阶段，可能会出现一些小问题哦！${white} |"
    echo -e "| ${yellow}不过您可以给官方提交一些方案，用来给更新v6的提供一些思路哟${white}      |"
    echo -e "| ${yellow}用来帮助新的v6完善一下哦！${white}       |"
    hr
    echo -e "| 您是否想要尝试适用v6                  |"
    echo -e "| 1) 是的，我想试试！(不推荐，暂时有bug)                                                |"
    echo -e "| 2) 不了，我还是用旧版本吧！(推荐)                                                 |"
    echo -e "| 3) 是的，以后也直接启动 v6 吧！(不推荐)              |"
    echo -e "| 4) 不了，以后也直接启动 v5 吧！(不推荐)                |"
    quit_footer
    while true; do
      read -p "${cyan}###### 选择吧！小伙伴:${white} " -e input
      case "${input}" in
        1)
          launch_kiauh_v6
          break;;
        2)
          launch_kiauh_v5
          break;;
        3)
          save_startup_version 6
          launch_kiauh_v6
          break;;
        4)
          save_startup_version 5
          launch_kiauh_v5
          break;;
        Q|q)
          echo -e "${green}###### 请准备愉快玩耍吧！! ######${white}"; echo
          exit 0;;
        *)
          error_msg "您的输入有问题哦！KIAUH酱不理解\n";;
      esac
    done && input=""
  fi
}

check_if_ratos
check_euid
init_logfile
set_globals
kiauh_update_dialog
read_kiauh_ini
init_ini
main
